﻿using Shake.Business.Infrastructures;
using Shake.Domain.Filters;
using Shake.Domain.Models;
using Shake.Framework.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shake.Business.Services
{
    public class UserService : IUserService
    {
        public IRepository Repository { get; set; }

        public List<User> GetUsers(UserFilter filter)
        {
            var factory = Repository.CreateSessionFactory();
            using (var session = factory.GetCurrentSession())
            {
                var query = session.QueryOver<User>();
                if (!string.IsNullOrEmpty(filter.NameOrNumber))
                {
                    query = query.Where(t => t.Name.Contains(filter.NameOrNumber) || t.Number.Contains(filter.NameOrNumber));
                }

                var results = query.List().ToList();
                return results;
            }
        }

        public void Save(List<User> users)
        {
            foreach (var user in users)
            {
                if (string.IsNullOrEmpty(user.Id))
                {
                    user.Id = Guid.NewGuid().ToString("N");
                    Repository.InsertMany(users);
                }
                else
                {
                    Repository.Update(user);
                }
            }
        }

        public void Remove(List<User> users)
        {
            Repository.DeleteMany(users);
        }

        public User GetFirstUser()
        {
            var factory = Repository.CreateSessionFactory();
            using (var session = factory.GetCurrentSession())
            {
                var query = session.QueryOver<User>();
                return query.Take(1).List().FirstOrDefault();
            }
        }
    }
}
